<template>
  <div>
    <Row>
      <i-col>
        <Form ref="tabParam" :model="tabParam" label-position="right" inline @keyup.enter.native="handleSearch">
          <!--<Row>-->
          <!--<i-col>-->
          <FormItem label="箱号：">
            <Input type="text" v-model="tabParam.containerNo" clearable style="width:120px"></Input>
          </FormItem>

          <FormItem label="箱属：">
            <!--<Select v-model="tabParam.containerUsers" multiple style="width:200px" filterable clearable>-->
            <!--<template v-for="item in containerUsersDict">-->
            <!--<Option :value="item" :key="item">{{ item }}</Option>-->
            <!--</template>-->
            <!--</Select>-->
            <selectAuto
              v-model="tabParam.containerUsers" field="containerOwner" label="containerOwner" search-keys="containerOwner,py" :dataList="containerUsersDict" :dropAll="true" :width="200"></selectAuto>
          </FormItem>

          <FormItem label="箱型：">
            <!--<Select v-model="tabParam.containerTypes" style="width:200px;height: 45px;overflow: hidden" filterable>-->
            <!--<template v-for="item in searchDict.containerTypesDict">-->
            <!--<Option :value="item" :key="item">{{ item }}</Option>-->
            <!--</template>-->
            <!--</Select>-->
            <selectAuto
              v-model="tabParam.containerTypes" field="containerType" label="containerType" search-keys="containerType,py" :dataList="containerTypesDict" :dropAll="true" :width="200"></selectAuto>
          </FormItem>

          <FormItem label="发站：">
            <!--<Select v-model="tabParam.startStationCodes" multiple style="width:200px" filterable>-->
            <!--<template v-for="item in searchDict.startStationCodesDict">-->
            <!--<Option :value="item">{{ item }}</Option>-->
            <!--</template>-->
            <!--</Select>-->
            <selectAuto
              v-model="tabParam.startStationCodes" field="stationName" label="stationName" search-keys="stationName,py" :dataList="stationCodesDict" :dropAll="true" :width="150" multiple></selectAuto>
          </FormItem>

          <FormItem label="发出时间段：">
            <DatePicker type="daterange" v-model="tabParam.startStationTimeArr" split-panels style="width: 200px"></DatePicker>
          </FormItem>

          <FormItem label="发出车次：">
            <Input type="text" v-model="tabParam.startTrainNumbers" clearable style="width:150px"></Input>
            <!--<Select v-model="tabParam.startTrainNumbers" multiple style="width:200px">-->
            <!--<template v-for="item in searchDict.startTrainNumbersDict">-->
            <!--<Option :value="item.value" :key="item.value">{{ item.label }}</Option>-->
            <!--</template>-->
            <!--</Select>-->
          </FormItem>

          <!--</i-col>-->
          <!--</Row>-->
          <!--<Row>-->
          <!--<i-col>-->

          <FormItem label="到站：">
            <!--<autoSelect v-model="tabParam.endStationCodes" multiple style="width:200px" filterable></autoSelect>-->
            <!--<template v-for="item in searchDict.endStationCodesDict">-->
            <!--<Option :value="item">{{ item }}</Option>-->
            <!--</template>-->
            <!--<autoSelect placeholder="请输入场站名称"-->
            <!--v-model="tabParam.endStationCodes" field="stationName" label="stationName" search-keys="stationName" :dataList="searchDict.endStationCodesDict" :dropAll="false" :width="'200px'" :top="'47px'"-->
            <!--:left="'-5px'"></autoSelect>-->
            <selectAuto
              v-model="tabParam.endStationCodes" field="stationName" label="stationName" search-keys="stationName,py" :dataList="stationCodesDict" :dropAll="true" :width="150" multiple></selectAuto>
          </FormItem>

          <FormItem label="到达时间段：">
            <DatePicker type="daterange" v-model="tabParam.endStationTimeArr" split-panels style="width: 200px"></DatePicker>
          </FormItem>

          <FormItem label="到达车次：">
            <Input type="text" v-model="tabParam.endTrainNumbers" clearable style="width:150px"></Input>
            <!--<Select v-model="tabParam.endTrainNumbers" multiple style="width:200px">-->
            <!--<template v-for="item in searchDict.endTrainNumbersDict">-->
            <!--<Option :value="item.value" :key="item.value">{{ item.label }}</Option>-->
            <!--</template>-->
            <!--</Select>-->
          </FormItem>
          <!--</i-col>-->
          <!--</Row>-->
          <!--<Row>-->
          <!--<i-col>-->
          <FormItem label="空重：">
            <RadioGroup v-model="tabParam.isEmpty">
              <Radio label="">全部</Radio>
              <Radio label="0">空</Radio>
              <Radio label="1">重</Radio>
            </RadioGroup>
          </FormItem>

          <FormItem label="状态：">
            <Select v-model="tabParam.curStateIds" multiple style="width:200px">
              <template v-for="item in curStateIdsDict">
                <Option :value="item.key">{{ item.key }}</Option>
              </template>
            </Select>
          </FormItem>

          <FormItem label="发货人：">
            <selectAuto
              v-model="tabParam.senders" field="sender" label="sender" search-keys="senderPingYin,sender" :dataList="senderDict" :dropAll="true" :width="200"></selectAuto>
            <!--<autoSelect-->
            <!--v-model="tabParam.senders" field="stationName" label="stationName" search-keys="stationName" :dataList="senderDict" :dropAll="false" :width="'200px'"></autoSelect>-->
            <!--<Select v-model="tabParam.senders" multiple style="width:200px">-->
            <!--<template v-for="item in searchDict.sendersDict">-->
            <!--<Option :value="item.value" :key="item.value">{{ item.label }}</Option>-->
            <!--</template>-->
            <!--</Select>-->
          </FormItem>

          <FormItem label="收货人：">
            <selectAuto
              v-model="tabParam.receiverDict" field="receiver" label="receiver" search-keys="receiverPingYin,receiver" :dataList="receiverDict" :dropAll="true" :width="200"></selectAuto>
            <!--<Input type="text" v-model="tabParam.receivers" clearable style="width:200px"></Input>-->
            <!--<Select v-model="tabParam.receivers" multiple style="width:200px">-->
            <!--<template v-for="item in searchDict.receiversDict">-->
            <!--<Option :value="item.value" :key="item.value">{{ item.label }}</Option>-->
            <!--</template>-->
            <!--</Select>-->
          </FormItem>

          <!--</i-col>-->
          <!--</Row>-->
        </Form>

        <div style="text-align: right;margin-bottom: 15px">
          <Button type="primary" @click="handleSearch" icon="ios-search">
            搜索
          </Button>
          <Button type="primary" @click="exportExcel">
            导出excel
          </Button>
        </div>

        <tablePage ref="orderReportNewTab" :api="getStreamMonitorDataByPage" :param="tabParamDeal" sort-name="startStationTime" sort-type="desc" showSizer :pageSizeOpts="[100,200,500]">
          <template slot-scope="props">
            <Table :columns="containerColumn" :data="props.data" :height="500"></Table>
          </template>
        </tablePage>
      </i-col>
    </Row>

    <xlinkModal v-model="operaModal.trackingShow" :title="'轨迹查看 -- '+operaModal.trackingShowTitle" width="1200">
      <trackingShow v-if="operaModal.trackingShow" :containerStateList="containerStateList" :subOrder="mainOrderCurrentRow"></trackingShow>
    </xlinkModal>

    <xlinkModal v-model="operaModal.historyShow" :title="'历史记录 -- '+operaModal.historyShowTitle" width="1200">
      <containerHistory v-if="operaModal.historyShow" :subOrder="mainOrderCurrentRow"></containerHistory>
    </xlinkModal>
  </div>
</template>
<script>
  import tablePage from '@components/table/tablePage.vue'
  import { exportUtil } from '@/vendor/exportInvoke'
  import { getStreamMonitorDataByPage } from '@api/containerPlatform/logistics'
  import xlinkModal from '@components/modal/xlinkModal'
  import trackingShow from './components/trackingShow'
  import containerHistory from './components/containerHistory'
  import moment from 'moment'
  import containerDictMixins from '../containerDictMixins'
  import _ from 'lodash'
  import selectAuto from '@/components/selectAuto'

  let dataFormat = 'YYYY-MM-DD'

  export default {
    name: 'tracking',
    mixins: [containerDictMixins],
    data () {
      let containerTypeList = []
      let containerStateList = []
      let stationPositionList = []
      let operaModal = {
        trackingShow: false,
        trackingShowTitle: '',
        historyShow: false,
        historyShowTitle: ''
      }
      let tabParam = {
        containerNo: '', // 箱号，模糊
        containerUsers: [], // 箱属，多选
        containerTypes: [], // 箱型，多选
        startStationCodes: '', // 发站码
        startStationTimeArr: [moment().subtract(7, 'days').format(dataFormat), moment().format(dataFormat)], // 发出时间段,开始时间和结束时间
        startStationTimeStart: moment().subtract(7, 'days').format(dataFormat) + ' 00:00:00',
        startStationTimeEnd: moment().format(dataFormat) + ' 23:59:59',
        startTrainNumbers: '', // 发出车次,
        endStationCodes: [], // 到站码，多选
        endStationTimeArr: '', // [moment().subtract(7, 'days').format(dataFormat), moment().format(dataFormat)], // 到达时间段，开始时间和结束时间
        endTrainNumbers: '', // 到达车次，多选
        isEmpty: '', // 空重  0：空 1： 重
        curStateIds: [], // 状态,多选
        senders: '', // 发货人
        receivers: '' // 收货人
      }
      let tabParamDeal = Object.assign({}, tabParam)
      let currentRow = null
      let searchDict = { // 搜索对象字典
        containerUsersDict: [], // 箱属字典
        containerTypesDict: [],
        startStationCodesDict: [],
        startTrainNumbersDict: [],
        endStationCodesDict: [],
        endTrainNumbersDict: [],
        curStateIdsDict: [],
        sendersDict: [],
        receiversDict: []
      }
      let containerColumn = [
        {
          title: '箱号',
          key: 'containerNo',
          fixed: 'left',
          width: 120
        },
        {
          title: '发站',
          key: 'sendStationName',
          width: 150
        },
        {
          title: '发出时间',
          key: 'startStationTime',
          width: 150
        },
        {
          title: '发出车次',
          key: 'startTrainNo',
          width: 150
        },
        {
          title: '到站',
          key: 'endStationName',
          width: 150
        },
        {
          title: '到达时间',
          key: 'endStationTime',
          width: 150
        },
        {
          title: '到达车次',
          key: 'endTrainNo',
          width: 150
        },
        {
          title: '空重',
          key: 'isEmpty',
          width: 80,
          render: (h, params) => {
            let item = params.row
            if (+item.isEmpty === 0) {
              return (<span>{'空'}</span>)
            }
            return (<span>{'重'}</span>)
          }
        },
        {
          title: '状态',
          key: 'curStateId',
          width: 100,
          render: (h, params) => {
            let item = params.row
            if (+item.curStateId === 30 || +item.curStateId === 31) {
              return (<span>{'在途'}</span>)
            } else if (+item.curStateId === 80) {
              return (<span>{'出局'}</span>)
            } else if (+item.curStateId !== 99) {
              return (<span>{'站内'}</span>)
            } else {
            }
          }
        },
        {
          title: '当前位置',
          key: 'curPosition',
          width: 100
        },
        {
          title: '发货人',
          key: 'sender',
          width: 150
        },
        {
          title: '收货人',
          key: 'receiver',
          width: 150
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          fixed: 'right',
          minWidth: 150,
          render: (h, params) => {
            let trackingBtn = (<i-button type="primary" size="small" style="margin-right: 5px;" onClick={() => {
              this.currentRow = params.row
              this.showTracking(params.row)
            }}>轨迹</i-button>)
            let historyBtn = (<i-button type="primary" size="small" style="margin-right: 5px;" onClick={() => {
              this.currentRow = params.row
              this.showHistory(params.row)
            }}>查看历史</i-button>)
            return ([trackingBtn, historyBtn])
          }
        }
      ]
      let datas = { containerTypeList, containerStateList, stationPositionList, operaModal, tabParam, containerColumn, getStreamMonitorDataByPage, searchDict, currentRow, tabParamDeal }
      return datas
    },
    methods: {
      showTracking (row) {
        this.mainOrderCurrentRow = row
        this.operaModal.trackingShowTitle = ' 箱号：' + row.containerNo + ' 发站：' + row.sendStationName + ' 到站：' + row.endStationName + ' 发货人：' + row.sender + ' 收货人：' + row.receiver + ' 空重：' + (row.isEmpty === 0 ? ' 空' : ' 重') + ' 箱型：' + row.containerType
        this.operaModal.trackingShow = true
      },
      showHistory (row) {
        this.mainOrderCurrentRow = row
        this.operaModal.historyShowTitle = ' 箱号：' + row.containerNo + ' 箱属：' + (row.userName ? row.userName : '') + ' 箱型：' + row.containerType
        this.operaModal.historyShow = true
      },
      /**
       * TODO(搜索)
       * @date 2018/8/31 17:14
       */
      handleSearch (param) {
        // this.tabParam = Object.assign({}, this.tabParam)
        this.$refs['orderReportNewTab'].dataRefresh()
      },
      /**
       * TODO(导出 excle)
       * @auther zhangQ
       * @date 2018/9/4 10:06
       */
      exportExcel () {
        let param = Object.assign({}, this.tabParamDeal)
        param.page = 1
        param.pageSize = 0
        if (this.$refs['orderReportNewTab']._data.pagination && +this.$refs['orderReportNewTab']._data.pagination.total > 20000) {
          this.$Notice.error({
            title: '导出数据过多，最多2万条数据！'
          })
          return
        }
        getStreamMonitorDataByPage(param)
          .then(res => {
            if (res.data.isSuccess === 1) {
              let resDate = res.data.data.rows
              // let resColumns = JSON.parse(JSON.stringify(this.stationColumn))
              let result = this.fasetJson(resDate)
              exportUtil.export2Excel('物流监测' + Date.now(), result.columns, result.data)
            }
          })
      },
      fasetJson (data) {
        data.forEach((item) => {
          +item.isEmpty === 0 ? item.isEmptyCN = '空' : item.isEmptyCN = '重'
          if (+item.curStateId === 30 || +item.curStateId === 31) {
            item.curStateIdCN = '在途'
          } else if (+item.curStateId === 80) {
            item.curStateIdCN = '出局'
          } else if (+item.curStateId !== 99) {
            item.curStateIdCN = '站内'
          }
        })
        let result = {
          columns: [{ title: '箱号', key: 'containerNo' },
            { title: '发站', key: 'sendStationName' },
            { title: '发出时间', key: 'startStationTime' },
            { title: '发出车次', key: 'startTrainNo' },
            { title: '到站', key: 'endStationName' },
            { title: '到达车次', key: 'endTrainNo' },
            { title: '到达时间', key: 'endStationTime' },
            { title: '到达车次', key: 'endTrainNo' },
            { title: '空重', key: 'isEmptyCN' },
            { title: '状态', key: 'curStateIdCN' },
            { title: '当前位置', key: 'curPosition' },
            { title: '发货人', key: 'sender' },
            { title: '收货人', key: 'receiver' }
          ],
          data: data
        }
        return result
      }
    },
    watch: {
      tabParam: {
        handler (val, oldval) {
          // 处理状态
          let curStateIds = []
          this.tabParam.curStateIds.forEach((item) => {
            let itemObjs = _.find(this.curStateIdsDict, { key: item })
            if (itemObjs && itemObjs.value && itemObjs.value.length > 0) {
              itemObjs.value.forEach((o) => {
                curStateIds.push(o.id)
              })
            }
          })
          let refreshParam = {
            userName: this.tabParam.containerUsers,
            containerType: this.tabParam.containerTypes, // && this.tabParam.containerTypes.length > 0 ? this.tabParam.containerTypes.join(',') : ''
            sendStationName: this.tabParam.startStationCodes && this.tabParam.startStationCodes.length > 0 ? this.tabParam.startStationCodes.join(',') : '',
            startTrainNo: this.tabParam.startTrainNumbers,
            endStationName: this.tabParam.endStationCodes && this.tabParam.endStationCodes.length > 0 ? this.tabParam.endStationCodes.join(',') : '',
            endTrainNo: this.tabParam.endTrainNumbers,
            isEmpty: this.tabParam.isEmpty,
            curStateId: curStateIds && curStateIds.length > 0 ? curStateIds.join(',') : '',
            sender: this.tabParam.senders,
            receiver: this.tabParam.receivers
          }
          // 时间处理
          if (this.tabParam.startStationTimeArr && this.tabParam.startStationTimeArr[0] && this.tabParam.startStationTimeArr[1]) {
            refreshParam.startStationTimeStart = moment(this.tabParam.startStationTimeArr[0]).format(dataFormat) + ' 00:00:00'
            refreshParam.startStationTimeEnd = moment(this.tabParam.startStationTimeArr[1]).format(dataFormat) + ' 23:59:59'
          }
          if (this.tabParam.endStationTimeArr && this.tabParam.endStationTimeArr[0] && this.tabParam.endStationTimeArr[1]) {
            refreshParam.endStationTimeStart = moment(this.tabParam.endStationTimeArr[0]).format(dataFormat) + ' 00:00:00'
            refreshParam.endStationTimeEnd = moment(this.tabParam.endStationTimeArr[1]).format(dataFormat) + ' 23:59:59'
          }
          this.tabParamDeal = refreshParam
        },
        deep: true
      }
    },
    mounted () {
      // this.getContainerStateList()
      this.getSenderListDB()
      this.getReceiverListDB()
      this.getContainersPositionListDB()
      this.getStateListDB()
      this.getContainersTypeListDB()
      this.getContainerOwnerListDB()
    },
    computed: {},
    components: { tablePage, xlinkModal, trackingShow, containerHistory, selectAuto }
  }
</script>
<style scoped>
  .lh-32 {
    line-height: 32px;
    margin-right: 5px;
  }

  .formMy:focus, .formMy:active {
    border: none;
  }
</style>
